import {useState, useEffect, useRef} from 'react'
import './App.css';
import {Button, Flex, Layout, Row, Col, Input} from 'antd'
import axios from 'axios'
import {marked} from 'marked'
import { parseMarkdown } from './utils/MarkdownUtils';
import { fetchArticle } from './utils/ArticleUtil';
import { fetchAudio } from './utils/TtsUtil';

const {Header, Content} = Layout
const {Search} = Input

const layoutStyle = {
  borderRadius: 8,
  overflow: 'hidden',
  width: 'calc(80% - 8px)',
  maxWidth: 'calc(80% - 8px)',
};

const headerStyle: React.CSSProperties = {
  textAlign: 'center',
  color: '#fff',
  height: 64,
  paddingInline: 48,
  lineHeight: '64px',
  backgroundColor: '#4096ff',
  alignItems:'center',
  display:'flex'
};

const contentStyle: React.CSSProperties = {
  // textAlign:'center',
  // display:'flex',
  // height: '700px',
  // lineHeight: '120px',
  // color: '#fff',
  // backgroundColor: '#0958d9',
  // margin:"0 16px"
};

const normalizeMarkdownHeaders = (markdownString) => {
  // 使用正则表达式匹配并调整标题格式
  return markdownString.replace(/^(#+)\s*\n+\s*(.+)$/gm, (match, hash, title) => {
      return `${hash} ${title.trim()}`;
  });
};

const addAudioIcon = (html) => {
  // 在每个 <p> 和 <h2> 前添加音频图标
  return html.replace(/(<\/h[1-6]>|<\/p>)/g, (match) => {
      return `<span class="audio-icon" style="color: blue; cursor: pointer;">🔊</span>${match}`;
  });
};

function App() {
  const containerRef = useRef(null);
  const [html, setHtml] = useState('')
  const [loading, setLoading] = useState(false)
  const [audio, setAudio] = useState(null);

  async function onSearch(url) {
    console.log('onSearch', url)
    if(!url) {
      console.log('no url')
      return;
    }
    const resp = await fetchArticle(url)
    setLoading(true)
    fetchArticle(url).then(async resp=> {
      const dataResult = await resp.json()
      console.log('Got data', dataResult)
      const {data, content} = parseMarkdown(dataResult)
      const newContent = normalizeMarkdownHeaders(content)
      const html = addAudioIcon(
        marked(newContent)
      )
      setHtml(html)
    }).finally(()=> {
      setLoading(false)
    })
  }
  const handleAudioIconClick = async (text) => {
    console.log(`音频图标被点击: ${text}`);
    const audioUrl = await fetchAudio(text);
    if (audioUrl) {
        const audioElement = new Audio(audioUrl);
        setAudio(audioElement); // 保存音频实例
        audioElement.play();
    }
    // 在这里添加调用后端的逻辑，比如发送文本以获取音频
  };

  useEffect(() => {
    const icons = containerRef.current.querySelectorAll('.audio-icon');
    icons.forEach((icon) => {
        icon.addEventListener('click', (event) => {
            const paragraphText = event.target.previousSibling.textContent; // 获取相应段落的文本
            handleAudioIconClick(paragraphText); // 调用处理函数
        });
    });

    // 清理事件监听器
    return () => {
        icons.forEach((icon) => {
            icon.removeEventListener('click', handleAudioIconClick);
        });
    };
  }, [html]);
  
  return (
    <Flex gap="middle" wrap  style={{margin: '16px 0'}}>
      <Layout>
        <Header style={headerStyle}>
          <Flex align='center' gap='small' style={{width:"100%"}}>
            <img src='/images/logo.png' style={{width: '68px'}} />
            <Flex justify='center'>
              <Search placeholder='Input article url to read' onSearch={onSearch} enterButton defaultValue="https://stacker.com/news/15-things-ai-can-and-cant-do"
               style={{width: '500px'}}
               loading={loading}
              ></Search>
            </Flex>

          </Flex>
          

        </Header>
        <Content style={contentStyle}>
          <Flex justify='center'>
            <div style={{width:'90%'}} ref={containerRef} dangerouslySetInnerHTML={{__html:html}}></div>
          </Flex>
        </Content>
      </Layout>
    </Flex>
  );
}

export default App;
